package com.coocaa.app.gamecenter.pages.arsenal.view;

import android.content.Context;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import com.coocaa.app.gamecenter.pages.arsenal.ItemViewAdapter;
import com.coocaa.app.gamecenter.pages.arsenal.data.WeaponItemData;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.R;
import com.tianci.appstore.utils.AsyncTask;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xfk on 2015/11/7.
 */
public class ItemListView extends HorizontalScrollView implements View.OnFocusChangeListener,
        View.OnKeyListener, View.OnClickListener {
    private static String tag = "arsenal";
    private ItemViewAdapter mAdapter;
    private Context mContext;
    private int totalItemNum = 0;
    private int showMaxItemIndex = 0;
    private int createItemNum = 0;
    private LinearLayout linearLayout;
    private List<ItemView> itemViewList;
	private ItemEventChangeInterface itemEventChangeInterface;
    private ItemViewDisplayToEndListener itemViewDisplayToEndListener;
    private SlideUpAndDownListener slideUpAndDownListener;
    private ItemFocusView.FocusChangedEvent focusChangedEvent;
    private ItemFocusView.FocusViewRevision focusViewRevision;
    private View currentFocusView;
    private Timer timer;
    private boolean isRequestFirstFocus = false;
    private boolean isSmoothEndRequestFocus = false;
    private boolean isResponseKey = true;
    private int currentPosition = 0;
    private int arsenalItemId = 0;
    private int currentKeyCode = 0;
    private int scrollX = 0;

    public interface ItemEventChangeInterface {
        public void itemFocusChange(String imgUrl);
        public boolean itemOnKeyDown(int keyCode);
        public void itemClick(String bigImgUrl);
    }

    public interface ItemViewDisplayToEndListener {
        public void itemViewDisplayToEnd(boolean b);
    }

    public interface SlideUpAndDownListener {
        public boolean slideUpAndDown(int arsenalItemId, int position, int keyCode);
    }

    public ItemListView(Context context) {
        super(context);
        mContext = context;
        timer = new Timer();
        linearLayout = new LinearLayout(context);
        itemViewList = new ArrayList<ItemView>();
        addView(linearLayout);
        setHorizontalScrollBarEnabled(false);

        focusViewRevision = new ItemFocusView.FocusViewRevision(CoocaaApplication.Div(0),
                CoocaaApplication.Div(0));
    }

    public void setAdapter(ItemViewAdapter adapter) {
        mAdapter = adapter;
    }

    public void setFocusChangedEvent(ItemFocusView.FocusChangedEvent focusChangedEvent) {
        LogUtils.i(tag, "setFocusChangedEvent");
        this.focusChangedEvent = focusChangedEvent;
    }

	public void setItemEventChangeInterface(ItemEventChangeInterface changeInterface) {
        this.itemEventChangeInterface = changeInterface;
    }

    public void setItemViewDisplayToEndListener(ItemViewDisplayToEndListener listener) {
        itemViewDisplayToEndListener = listener;
    }

    public void setSlideUpAndDownListener(SlideUpAndDownListener listener) {
        slideUpAndDownListener = listener;
    }

    public void setArsenalItemId(int arsenalItemId) {
        this.arsenalItemId = arsenalItemId;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    public void refreshUI() {
        totalItemNum = mAdapter.getCount();

        if(totalItemNum <= 0)
            return;

        int firstShowItem = 0;
        if(totalItemNum > 3)
            firstShowItem = 3;
        else
            firstShowItem = totalItemNum;

        for(int i = 0; i < firstShowItem; i++) {
            LayoutParams params = new LayoutParams(
                    CoocaaApplication.Div(285), ViewGroup.LayoutParams.MATCH_PARENT);
            View view = mAdapter.getView(i, null, null);
            view.setOnFocusChangeListener(this);
            view.setOnKeyListener(this);
            view.setOnClickListener(this);
            view.setContentDescription(arsenalItemId + "|" + i);
            if(focusChangedEvent != null)
                focusChangedEvent.registerView(view, focusViewRevision, this);
            linearLayout.addView(view, params);
            linearLayout.requestLayout();
            linearLayout.invalidate();
            createItemNum = view.getId();
            itemViewList.add((ItemView)view);
        }
        LogUtils.i(tag, "requestLayout");
        requestLayout();
    }

    public void requestItemFocus(int index) {
        if(linearLayout != null && linearLayout.getChildCount() > index) {
            if(timer != null)
                timer.schedule(timerTask, 100);
        }
    }

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            LogUtils.i(tag, "timerTask run");
            if(isRequestFirstFocus == true)
                return;
            AsyncTask.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    View v = itemViewList.get(0);
                    if(v == null) {
                        if(timer != null)
                            timer.schedule(timerTask, 100);
                        return;
                    }
                    int[] to = new int[2];
                    v.getLocationOnScreen(to);
                    if(to[0] == 0 || to[1] == 0) {
                        if(timer != null)
                            timer.schedule(timerTask, 100);
                        return;
                    }

                    v.requestFocus();
                    isRequestFirstFocus = true;
                }
            });
        }
    };

    public View getItemView(int index) {
        View view = null;
        if(itemViewList != null && itemViewList.size() > index)
            view  = itemViewList.get(index);
        return view;
    }

    /**
     * 根据显示位置设置焦点
     * @param pos
     */
    public void requestItemFocusByPos(int pos) {
        int currentId = 0;
        int newFocusIndex = 0;
        if(currentFocusView != null) {
            currentId = currentFocusView.getId();
            newFocusIndex = currentId + pos - currentPosition;
        } else {
            newFocusIndex = pos;
        }

        if(linearLayout != null) {
            if(linearLayout.getChildCount() > newFocusIndex)
                linearLayout.getChildAt(newFocusIndex).requestFocus();
            else
                linearLayout.getChildAt(linearLayout.getChildCount() - 1).requestFocus();
        }
    }

    /**
     * 根据显示位置设置焦点
     */
    public void setItemViewFocusable(boolean b) {
        LogUtils.i(tag, "setItemViewFocusable b = "+b);
        if(currentFocusView != null) {
            if(false)
                currentFocusView.setBackgroundResource(R.drawable.arsenal_item_selector);
            else
                currentFocusView.setBackgroundResource(R.drawable.arsenal_item_bg);
        }
    }

    public void onDestroy() {
        if(timer != null) {
            timer.cancel();
            timer = null;
        }

        if(itemViewList != null) {
            for(ItemView itemView: itemViewList) {
                if(itemView != null) {
                    linearLayout.removeView(itemView);
                    itemView.onDestroy();
                    itemView.destroyDrawingCache();
                }
            }

            itemViewList.clear();
        }

        if(currentFocusView != null) {
            currentFocusView.destroyDrawingCache();
            currentFocusView = null;
        }
    }

    private OnClickListener  onClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    };

    private void getCurrentPos(int focusIndex) {
        int[] locations = new int[2];
        int[] layoutLocations = new int[2];
        itemViewList.get(focusIndex).getLocationOnScreen(locations);
        this.getLocationOnScreen(layoutLocations);
        //加10防止由于不同分辨率计算误差导致的计算错误
        currentPosition = (locations[0] + 10 - layoutLocations[0]) / CoocaaApplication.Div(280);
        LogUtils.i(tag, "currentPosition = " + currentPosition);
    }

    private boolean isDisplayToEnd(int focusIndex) {

        if(focusIndex == 0) {
            if(totalItemNum <= 3)
                return true;
            else
                return false;
        }

        if(itemViewList.size() < totalItemNum) {
            return false;
        }

        if(itemViewList.size() > (focusIndex + 3 - currentPosition))
            return false;
        else
            return true;
    }

    @Override
    public void fling(int velocityY) {
        super.fling(velocityY / 2);
    }

    @Override
    public void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);

        if(x == scrollX && !isSmoothEndRequestFocus) {
            LogUtils.i(tag, "SmoothEndRequestFocus + id: "+currentFocusView.getId());
            isSmoothEndRequestFocus = true;
            if(currentKeyCode == KeyEvent.KEYCODE_DPAD_RIGHT
                && itemViewList.size() > currentFocusView.getId() + 1) {
                itemViewList.get(currentFocusView.getId() + 1).requestFocus();
            }else if(currentKeyCode == KeyEvent.KEYCODE_DPAD_LEFT
                    && currentFocusView.getId() > 0) {
                itemViewList.get(currentFocusView.getId() - 1).requestFocus();
            } else {
                LogUtils.i(tag, "not SmoothEndRequestFocus");
            }
        }
        this.getMeasuredWidth();
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        if (b) {

            if(!isRequestFirstFocus) {
                if(timer != null) {
                    timer.cancel();
                    timer = null;
                }
                isRequestFirstFocus = true;
            }
            LogUtils.i(tag, "view.getId(); " + view.getId() + ", createItemNum: " + createItemNum +
                    ", totalItemNum: " + totalItemNum);
//            view.setBackgroundResource(R.drawable.arsenal_item_selector);
            view.setBackgroundDrawable(null);
            getCurrentPos(view.getId());
            if(itemEventChangeInterface != null &&view instanceof ItemView) {
                WeaponItemData weaponItemData = ((ItemView) view).getWeaponItemData();
                itemEventChangeInterface.itemFocusChange(weaponItemData.middleUrl);
            }

            int nextLoadId, nextHideId;
            if(currentKeyCode == KeyEvent.KEYCODE_DPAD_RIGHT
                    && currentPosition == 2) {
                nextLoadId = 3 - currentPosition +view.getId();
                nextHideId = view.getId() - currentPosition - 1;
                if(nextLoadId < itemViewList.size()) {
                    itemViewList.get(nextLoadId).recycleItemCache(false);
                }

                if(nextHideId >= 0) {
                    itemViewList.get(nextHideId).recycleItemCache(true);
                }
            }

            if(currentKeyCode == KeyEvent.KEYCODE_DPAD_LEFT
                    && currentPosition == 0) {
                nextLoadId = 3 - currentPosition +view.getId();
                nextHideId = view.getId() - currentPosition - 1;
                if(nextLoadId < itemViewList.size()) {
                    itemViewList.get(nextLoadId).recycleItemCache(true);
                }

                if(nextHideId >= 0) {
                    itemViewList.get(nextHideId).recycleItemCache(false);
                }
            }


            if(itemViewList.size() == view.getId()+1 && itemViewList.size() < totalItemNum) {
                LogUtils.i(tag, "add new item view");
                LayoutParams params = new LayoutParams(
                        CoocaaApplication.Div(285), ViewGroup.LayoutParams.MATCH_PARENT);
                View v = mAdapter.getView(view.getId()+1, null, null);
                v.setOnFocusChangeListener(this);
                v.setOnKeyListener(this);
                v.setOnClickListener(this);
                v.setContentDescription("");
                v.setContentDescription(arsenalItemId + "|" + view.getId() + 1);
                if(focusChangedEvent != null)
                    focusChangedEvent.registerView(v, focusViewRevision, this);
                linearLayout.addView(v, params);
                createItemNum = v.getId();
                itemViewList.add((ItemView) v);
                linearLayout.requestLayout();
                this.requestLayout();
            }

            currentFocusView = view;
            boolean displayToEnd = isDisplayToEnd(view.getId());
            LogUtils.i(tag, "isDisplayToEnd: " + displayToEnd);
            if(itemViewDisplayToEndListener != null)
                itemViewDisplayToEndListener.itemViewDisplayToEnd(displayToEnd);

            isResponseKey = true;
            LogUtils.i(tag, "focuschange isResponseKey: "+isResponseKey);
        } else {
            view.setBackgroundResource(R.drawable.arsenal_item_bg);
        }
    }

    int lastHorizontalScrollRange = 0;
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {

        if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {

            if(itemEventChangeInterface != null) {
                //ArsenalLayout处理，如果为true说明全屏展示
                if(itemEventChangeInterface.itemOnKeyDown(keyEvent.getKeyCode()))
                    return true;
            }

            if(keyEvent.getRepeatCount() % 2!= 0)
                return true;
            LogUtils.i(tag, "keydown isResponseKey: "+isResponseKey+", id: "+view.getId());
            if(!isResponseKey && (keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT
                || keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT
                || keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP
                || keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN
                || keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER)) {
                return true;
            }

            currentKeyCode = keyEvent.getKeyCode();
            if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
                if(view.getId() >= itemViewList.size() - 1) {
                    return true;
//                    if(slideUpAndDownListener != null)
//                        return slideUpAndDownListener.slideUpAndDown(arsenalItemId, currentPosition, KeyEvent.KEYCODE_DPAD_RIGHT);
                } else if(currentPosition == 2){

                    LogUtils.i(tag,"ScrollRange request = "+CoocaaApplication.Div(285) * (view.getId() + 2)+
                            ", now = "+this.computeHorizontalScrollRange());
                    if(this.computeHorizontalScrollRange() < CoocaaApplication.Div(285) * (view.getId() + 2)) {
                        LogUtils.i(tag, "listview not refresh return");
                        return true;
                    } else {
                        lastHorizontalScrollRange = this.computeHorizontalScrollRange();
                    }

                    isResponseKey = false;
                    isSmoothEndRequestFocus = false;
                    scrollX = CoocaaApplication.Div(285) * (view.getId() - 1);

                    LogUtils.i(tag, "scrollToX: " + scrollX+", nowX: "+this.getScrollX());
                    this.smoothScrollTo(scrollX, 0);
                    return true;
                } else {
                    isResponseKey = false;
                    itemViewList.get(view.getId() + 1).requestFocus();
                    return true;
                }

            }

            if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
                if(view.getId() == 0) {
                    return true;
//                    if(slideUpAndDownListener != null)
//                        return slideUpAndDownListener.slideUpAndDown(arsenalItemId, currentPosition, KeyEvent.KEYCODE_DPAD_LEFT);
                } else if(currentPosition == 0) {
                    isResponseKey = false;
                    isSmoothEndRequestFocus = false;
                    scrollX = CoocaaApplication.Div(285) * (view.getId() - 1);
                    LogUtils.i(tag, "scrollX: " + scrollX+", nowX: "+this.getScrollX());
                    this.smoothScrollTo(scrollX, 0);
                    return true;
                } else {
                    isResponseKey = false;
                    itemViewList.get(view.getId() - 1).requestFocus();
                    return true;
                }

            }

            if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN
                    || keyEvent.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
                if(slideUpAndDownListener != null)
                    return slideUpAndDownListener.slideUpAndDown(arsenalItemId, currentPosition, keyEvent.getKeyCode() );
            }
        }
        return false;
    }

    @Override
    public void onClick(View view) {
        if(itemEventChangeInterface != null &&view instanceof ItemView) {
            WeaponItemData weaponItemData = ((ItemView) view).getWeaponItemData();
            itemEventChangeInterface.itemClick(weaponItemData.bigUrl);
        }
    }
}
